package com.store.app.activity;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.bean.BitmapBean;
import com.store.app.bean.EventBusBean;
import com.store.app.bean.OneYuanBuyUpdateBean;
import com.store.app.http.Stores;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.stores.MultipartEntity;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.SettingData;
import com.store.app.utils.Utils;
import com.store.app.utils.UtilsBitmap;
import com.store.app.widget.DateTimeButton;
import com.yalantis.ucrop.CropUtils;
import com.yalantis.ucrop.UCrop;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2016/4/12.
 * 创建一元购
 */
public class OneYuanBuy_CreatActivity extends BaseActivity implements IOnHttpListener {
    //返回
    private LinearLayout right_lin;
    //标题
    private TextView title_tv;
    //活动名称
    private EditText name_edit;
    //商品名
    private EditText goodsname_edit;
    //商品价格
    private EditText goodsprice_edit;
    //活动人数
    private EditText person_edit;
    //有效期
    private TextView data_tv;
    private DateTimeButton data_img;
    private ImageView img1;
    //提交
    private TextView post_tv;
    //             活动名        商品名称            商品价格        截止日期    活动人数
    private String s_name_edit, s_goodsname_edit, s_goodsprice_edit, s_data_tv, s_person_edit;
    private static final int FLAG_CHOOSE_IMG = 5;
    private static final int FLAG_CHOOSE_PHONE = 6;
    private static final int FLAG_MODIFY_FINISH = 7;
    private static final int MSG_IMG_FAILED = 1;
    private static final int MSG_IMG_SUCC = 2;
    private static String localTempImageFileName = "";
    //上传的bitmap
    Bitmap newbitmap1 = null;
    private boolean isInitImage;

    private NetRequest netRequest;
    private String pic_id;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case MSG_IMG_FAILED:
                    dismissProgressDialog();
                    Toast.makeText(OneYuanBuy_CreatActivity.this, "图片上传失败！", Toast.LENGTH_SHORT).show();
                    break;
                case MSG_IMG_SUCC:
                    Log.i("mylog", "图片id " + (String) msg.obj);
                    netRequest.requestAddOneYuanBuy(1, s_name_edit, s_data_tv, s_goodsname_edit,
                            s_goodsprice_edit, s_person_edit, (String) msg.obj);
                    break;
                default:
                    break;
            }
        }
    };
    private BitmapBean bitmapBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_oneyuanbuy_creat);
        initView();
        initData();
        initListeners();
    }

    private void initData() {
        title_tv.setText("定时开");

        netRequest = new NetRequest(this);

        String title = getIntent().getStringExtra("title");
        if (!TextUtils.isEmpty(title)) {
            name_edit.setText(title);
            goodsname_edit.setText(getIntent().getStringExtra("shopName"));
            goodsprice_edit.setText(getIntent().getStringExtra("shopPrice"));
            person_edit.setText(getIntent().getStringExtra("limitCount"));

            DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .cacheInMemory(true)
                    .showImageOnLoading(R.drawable.default_picture_s)
                    .showImageOnFail(R.drawable.default_picture_s)
                    .showStubImage(R.drawable.default_picture_s)
                    .imageScaleType(ImageScaleType.EXACTLY)
                    .bitmapConfig(Bitmap.Config.RGB_565)
                    .build();

            isInitImage = true;
//            boolean isTrue = getIntent().getBooleanExtra(OneYuan_DetailsActivity.ISTRUE, false);
//            if (isTrue) {
//                isInitImage = false;
//            }

            pic_id = getIntent().getStringExtra("pic_id");
            ImageLoader.getInstance().displayImage(getIntent().getStringExtra("pic"), img1, options);
        }

    }

    private void initListeners() {
        findViewById(R.id.public_ll_return).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        img1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showMyDialog();
            }
        });
        right_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                post();
            }
        });
        data_img.setonDateListener(new DateTimeButton.DateListener() {

            @Override
            public void getdate(Calendar calendar) {
                String s_date = Utils.getTime1(calendar);
                Log.v("zyl", "s_date:" + s_date);
                if (!TextUtils.isEmpty(s_date)) {
                    data_tv.setText(s_date);
                }
            }
        });
        post_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                post();
            }
        });
    }

    public void post() {
        s_name_edit = name_edit.getText().toString().trim();
        if (TextUtils.isEmpty(s_name_edit)) {
            Toast.makeText(OneYuanBuy_CreatActivity.this, "请输入活动名称！", Toast.LENGTH_SHORT).show();
            return;
        }

        s_goodsname_edit = goodsname_edit.getText().toString().trim();
        if (TextUtils.isEmpty(s_goodsname_edit)) {
            Toast.makeText(OneYuanBuy_CreatActivity.this, "请输入商品名称！", Toast.LENGTH_SHORT).show();
            return;
        }


        s_goodsprice_edit = goodsprice_edit.getText().toString();
        if (TextUtils.isEmpty(s_goodsprice_edit)) {
            Toast.makeText(OneYuanBuy_CreatActivity.this, "请输入商品价格！", Toast.LENGTH_SHORT).show();
            return;
        }
        s_goodsprice_edit = MoneyUtil.formatMoney(s_goodsprice_edit);

        s_data_tv = data_tv.getText().toString();
        if (TextUtils.isEmpty(s_data_tv)) {
            Toast.makeText(OneYuanBuy_CreatActivity.this, "请选择截止日期！", Toast.LENGTH_SHORT).show();
            return;
        }

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try

        {

            Date d1 = df.parse(s_data_tv);

            Date d2 = new Date();

            long diff = d1.getTime() - d2.getTime();

            long days = diff / (1000 * 60);
            if (days < 10) {
                Toast.makeText(OneYuanBuy_CreatActivity.this, "请输入10分钟后的截止时间！", Toast.LENGTH_SHORT).show();
                return;
            }
        } catch (Exception e)

        {

        }

        s_person_edit = person_edit.getText().toString();
        if (TextUtils.isEmpty(s_person_edit)) {
            Toast.makeText(OneYuanBuy_CreatActivity.this, "请输入达标人次！", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            Integer i_person_edit = Integer.parseInt(s_person_edit);
            if (i_person_edit <= 0) {
                Toast.makeText(OneYuanBuy_CreatActivity.this, "输入的活动人数需大于0！", Toast.LENGTH_SHORT).show();
                return;
            }
            double d_goodsprice_edit = Double.parseDouble(s_goodsprice_edit);
            if (d_goodsprice_edit < 1) {
                Toast.makeText(OneYuanBuy_CreatActivity.this, "输入的商品价格需大于或等于1！", Toast.LENGTH_SHORT).show();
                return;
            }
            if (d_goodsprice_edit > i_person_edit) {
                Toast.makeText(OneYuanBuy_CreatActivity.this, "达标人次不能小于商品价格，请重新设置！", Toast.LENGTH_SHORT).show();
                return;
            }
        } catch (Exception e) {
            Toast.makeText(OneYuanBuy_CreatActivity.this, "输入的达标人次需大于0！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (newbitmap1 == null) {

            if (isInitImage) {
                Log.v("zyl", "是初始化的情况");
            } else {
                Log.v("zyl", "非初始化的情况");
                Toast.makeText(OneYuanBuy_CreatActivity.this, "请选择要上传的商品图片！", Toast.LENGTH_SHORT).show();
                return;
            }


        }
        if(Utils.isFastClick()){
            return;
        }

        Log.v("zyl", "isInitImage:" + isInitImage);
        showProgressDialog("添加定时开", "提交中……", true);


        if (newbitmap1 != null) {

            if (bitmapBean.getIsBm() != null) {
                //上传图片
                netRequest.requestUploadPic(4, bitmapBean.getIsBm());
            }
//            new uploadtask().start();
        } else {
            Message msg = Message.obtain();
            msg.what = MSG_IMG_SUCC;
            msg.obj = pic_id;
            mHandler.sendMessage(msg);
        }
        try {
            InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),
                        0);

            }
        } catch (Exception e) {
        }
    }

    private void showMyDialog() {
        new AlertDialog.Builder(OneYuanBuy_CreatActivity.this)
                .setTitle("请选择图片来源")
                .setItems(new String[]{"相册", "相机"},
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                if (which == 0) {
                                    Intent intent = new Intent(
                                            Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                    startActivityForResult(intent,
                                            FLAG_CHOOSE_IMG);


                                } else if (which == 1) {
                                    String status = Environment
                                            .getExternalStorageState();
                                    if (status
                                            .equals(Environment.MEDIA_MOUNTED)) {
                                        try {
                                            localTempImageFileName = "";
                                            localTempImageFileName = String
                                                    .valueOf((new Date())
                                                            .getTime())
                                                    + ".png";
                                            File filePath = SettingData.FILE_PIC_SCREENSHOT;
                                            if (!filePath.exists()) {
                                                filePath.mkdirs();
                                            }
                                            Intent intent = new Intent(
                                                    MediaStore.ACTION_IMAGE_CAPTURE);
                                            File f = new File(filePath,
                                                    localTempImageFileName);
                                            // localTempImgDir和localTempImageFileName是自己定义的名字
                                            Uri u = Uri.fromFile(f);
                                            intent.putExtra(
                                                    MediaStore.Images.Media.ORIENTATION,
                                                    0);
                                            intent.putExtra(
                                                    MediaStore.EXTRA_OUTPUT,
                                                    u);
                                            startActivityForResult(
                                                    intent,
                                                    FLAG_CHOOSE_PHONE);
                                        } catch (ActivityNotFoundException e) {
                                            //
                                        }
                                    }
                                }

                            }
                        }).show();
    }

    private void initView() {
        title_tv = (TextView) findViewById(R.id.tvTitle);
        right_lin = (LinearLayout) findViewById(R.id.public_ll_right);
        name_edit = (EditText) findViewById(R.id.oneyb_creat_edit_name);
        img1 = (ImageView) findViewById(R.id.oneyb_creat_img);
        goodsname_edit = (EditText) findViewById(R.id.oneyb_creat_goodsname);
        goodsprice_edit = (EditText) findViewById(R.id.oneyb_creat_goodsprice);
        data_tv = (TextView) findViewById(R.id.oneyb_creat_date);
        data_img = (DateTimeButton) findViewById(R.id.oneyb_creat_date_btn);
        person_edit = (EditText) findViewById(R.id.oneyb_creat_person);

        post_tv = (TextView) findViewById(R.id.addcoupns1_tv_post);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == FLAG_CHOOSE_IMG && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {

                    CropUtils.startCropActivity(uri, OneYuanBuy_CreatActivity.this, 5, 5);
                }
            }
        } else if (requestCode == FLAG_CHOOSE_PHONE && resultCode == RESULT_OK) {

            File f = new File(SettingData.FILE_PIC_SCREENSHOT, localTempImageFileName);
            Uri uri = Uri.fromFile(f);
            if (uri != null) {
                UtilsBitmap.getCompressUri(uri);
                CropUtils.startCropActivity(uri, OneYuanBuy_CreatActivity.this, 5, 5);
            }

        } else if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
            //剪切成功
            if (data != null) {
                final Uri resultUri = UCrop.getOutput(data);
                bitmapBean = UtilsBitmap.addFilePath3(resultUri.getPath(), this);

                if (bitmapBean.getIsBm() != null) {
                    newbitmap1 = bitmapBean.getBitmap();
                    img1.setImageBitmap(bitmapBean.getBitmap());
                }
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            //剪切失败
            Toast.makeText(OneYuanBuy_CreatActivity.this, "图片剪切失败！", Toast.LENGTH_SHORT)
                    .show();
        }

    }

    @Override
    public void onAfinalFail() {
        dismissProgressDialog();
        Toast.makeText(OneYuanBuy_CreatActivity.this, "发布失败！", Toast.LENGTH_SHORT)
                .show();
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        Log.v("zyl", "onExecuteSuccess:" + result);
        if (requestId == 1) {
            dismissProgressDialog();
            Toast.makeText(OneYuanBuy_CreatActivity.this, "发布成功！", Toast.LENGTH_SHORT)
                    .show();
            EventBus.getDefault().post(new OneYuanBuyUpdateBean(1));
            EventBus.getDefault().post(new EventBusBean(203));
            finish();
        } else if (requestId == 4) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                String doc_id = jsonObject.getString("doc_id");
                netRequest.requestAddOneYuanBuy(1, s_name_edit, s_data_tv, s_goodsname_edit,
                        s_goodsprice_edit, s_person_edit, doc_id);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        Log.v("zyl", "onExecuteFail:" + msg);
        if (requestId == 1) {
            dismissProgressDialog();
            Toast.makeText(OneYuanBuy_CreatActivity.this, "发布失败！", Toast.LENGTH_SHORT)
                    .show();
        }

    }


    /**
     * 上传图片
     */
    private class uploadtask extends Thread {

        public void run() {

            String s_bitmap1 = null;

            Bitmap bitmap = null;

            bitmap = newbitmap1;


            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 10, stream);
            InputStream in = new ByteArrayInputStream(stream.toByteArray());
            DefaultHttpClient httpclient = new DefaultHttpClient();
            try {
                HttpPost httppost = new HttpPost(Stores.http
                        + "/ops-storage/storage/upload");

                MultipartEntity reqEntity = new MultipartEntity();

                reqEntity.addPart("app_token", MainActivity.app_token);
                reqEntity.addPart("category", "oss_community");
                reqEntity.addPart("subffix", "jpg");
                reqEntity.addPart("up_load_file", "pic.jpg", in);
                httppost.setEntity(reqEntity);
                HttpResponse response = null;
                response = httpclient.execute(httppost);
                response.getStatusLine().toString();
                String strResult = EntityUtils.toString(response.getEntity());
                JSONObject obj = new JSONObject(strResult);

                String rsp_code = obj.getString("rsp_code");
                if (rsp_code.equals("succ")) {//图片上传成功


                    JSONObject data = obj.getJSONObject("data");
                    String doc_id = data.getString("doc_id");
                    s_bitmap1 = doc_id;
                    Log.v("zyl", "图片上传成功：" + s_bitmap1);

                } else {
                    Message msg = Message.obtain();
                    msg.what = MSG_IMG_FAILED;
                    msg.obj = "图片上传失败";
                    mHandler.sendMessage(msg);
                    return;
                }
                in.close();
                stream.close();

            } catch (Exception e) {
                Message msg = Message.obtain();
                msg.what = MSG_IMG_FAILED;
                msg.obj = "图片上传失败";
                mHandler.sendMessage(msg);
                return;
            }

            if (!TextUtils.isEmpty(s_bitmap1)) {
                Message msg = Message.obtain();
                msg.what = MSG_IMG_SUCC;
                msg.obj = s_bitmap1;
                mHandler.sendMessage(msg);

            } else {
                Message msg = Message.obtain();
                msg.what = MSG_IMG_FAILED;
                msg.obj = "图片上传失败";
                mHandler.sendMessage(msg);
                return;
            }
        }

    }
}
